import { ref } from "vue";
import { defineStore } from "pinia";
import request from "@/lib/request.js";
import { handleRes } from "@/lib/common.js";
import useAppStore from "./app.js";
import useAuthStore from "./auth.js";
const appStore = useAppStore();
const authStore = useAuthStore();
const useWxStore = defineStore('wx',()=>{
	const openId = ref("")
	const wxAuth = ref(false)
	function wxAuthPromise() {
	  var that = this;
	  return new Promise(function (resolve, reject) {
	    appStore.uniAuth().then((code) => {
	      console.log(code);
	      request({
	        url: "/pms/wx/qlogin?code=" + code,
	        method: "POST",
	      })
	        .then((res) => {
	          handleRes(res);
	          console.log("--微信快速登录--");
	          console.log(res);
	          authStore.isLogin = true;
	          authStore.token = res.data.token;
	          uni.setStorageSync("token", res.data.token);
	          authStore.userId = res.data.id;
			  authStore.uid = res.data.id;
	          that.wxAuth = true;
	          resolve(true);
	        })
	        .catch((e) => {
	          console.log(e);
	          resolve(false);
	        });
	    });
	  });
	}
	// 微信登录
	function doWxAuth() {
	  var that = this;
	  // 如果未登录使用微信登录
	  if (authStore.isLogin == false) {
	    appStore.uniAuth().then((code) => {
	      console.log(code);
	      request({
	        url: "/pms/wx/qlogin?code=" + code,
	        method: "POST",
	      })
	        .then((res) => {
	          // handleRes(res)
	          console.log("--微信快速登录--");
	          console.log(res);
	          authStore.isLogin = true;
	          authStore.token = res.data.token;
	          uni.setStorageSync("token", res.data.token);
	          authStore.userId = res.data.id;
			  authStore.uid = res.data.id;
	          this.wxAuth = true;
	        })
	        .catch((e) => {
	          console.log(e);
	        });
	    });
	  }
	}
	return { openId, wxAuth,wxAuthPromise, doWxAuth}
})
export default useWxStore;
